<?php
namespace app\common\logic;

use think\facade\Db;
use TencentAds\TencentAds;
use TencentAds\Exception\TencentAdsResponseException;
use TencentAds\Exception\TencentAdsSDKException;

/**
 * 腾讯广告SDK逻辑处理类
 * Class TencentAdsLogic
 * @package app\common\logic
 */
class TencentAdsLogic
{
    private $appId;
    private $appSecret;
    private $accessToken;
    private $accountId;
    private $tads;
    
    /**
     * 构造函数
     */
    public function __construct()
    {
        $config = \app\common\model\TencentAdsConfig::getConfig();
        $this->appId = $config['app_id'] ?? '';
        $this->appSecret = $config['app_secret'] ?? '';
        $this->accountId = $config['account_id'] ?? '';
        $this->accessToken = $this->getAccessToken();
        
        $this->tads = TencentAds::init([
            'app_id' => $this->appId,
            'app_secret' => $this->appSecret,
            'access_token' => $this->accessToken,
            'is_debug' => $config['is_sandbox'] ?? false,
        ]);
        $this->tads->useSandbox($config['is_sandbox'] ?? false); // 设置是否使用沙箱环境
    }
    
    /**
     * 获取访问令牌
     * @return string
     */
    private function getAccessToken()
    {
        try {
            $result = $this->tads->oauth()->authorize([
                'client_id' => $this->appId,
                'client_secret' => $this->appSecret,
                'grant_type' => 'client_credentials',
            ]);
            return $result->getAccessToken();
        } catch (TencentAdsResponseException $e) {
            throw new \Exception('获取access_token失败：' . $e->getMessage());
        } catch (TencentAdsSDKException $e) {
            throw new \Exception('SDK调用异常：' . $e->getMessage());
        }
    }
    
    /**
     * 创建朋友圈广告
     * @param array $params 广告参数
     * @return array
     */
    public function createMomentAd($params)
    {
        try {
            // 创建广告计划
            $campaignId = $this->tads->campaigns()->add([
                'account_id' => $this->accountId,
                'campaign_name' => $params['campaign_name'],
                'campaign_type' => 'NORMAL',
                'promoted_object_type' => $params['promoted_object_type'] ?? 'LINK',
                'daily_budget' => $params['campaign_daily_budget'] ?? 1000000, // 计划日预算，单位：分
                'configured_status' => $params['campaign_status'] ?? 'NORMAL' // 计划状态：NORMAL或SUSPEND
            ]);

            // 创建广告组
            $adgroupId = $this->tads->adgroups()->add([
                'account_id' => $this->accountId,
                'campaign_id' => $campaignId,
                'adgroup_name' => $params['adgroup_name'],
                'site_set' => ['SITE_SET_MOMENTS'], // 投放位置：朋友圈
                'billing_event' => $params['billing_event'] ?? 'CLICK', // 计费方式：CPC
                'bid_amount' => $params['bid_amount'] ?? 100, // 出价，单位：分
                'daily_budget' => $params['daily_budget'] ?? 1000000, // 单位：分
                'targeting' => [
                    'age' => $params['targeting_age'] ?? ['AGE_18_23', 'AGE_24_30', 'AGE_31_40', 'AGE_41_49', 'AGE_ABOVE_50'],
                    'gender' => $params['targeting_gender'] ?? ['MALE', 'FEMALE'],
                    'geo_location' => [
                        'location_types' => ['LIVE_IN'],
                        'regions' => $params['targeting_regions'] ?? []
                    ],
                    'user_os' => $params['targeting_os'] ?? ['IOS', 'ANDROID'],
                    'network_type' => $params['targeting_network'] ?? ['WIFI', '2G', '3G', '4G', '5G'],
                    'user_interest_tags' => $params['targeting_interests'] ?? [],
                    'behavior_interest' => $params['targeting_behaviors'] ?? []
                ],
                'begin_date' => $params['begin_date'] ?? date('Y-m-d'), // 投放开始日期
                'end_date' => $params['end_date'] ?? '', // 投放结束日期，空表示持续投放
                'schedule_type' => $params['schedule_type'] ?? 'SCHEDULE_FROM_NOW', // 投放时间类型
                'time_series' => $params['time_series'] ?? '111111111111111111111111' // 24小时投放时段
            ]);

            // 创建广告创意
            $creativeId = $this->tads->creatives()->add([
                'account_id' => $this->accountId,
                'campaign_id' => $campaignId,
                'adgroup_id' => $adgroupId,
                'creative_name' => $params['creative_name'],
                'title' => $params['title'],
                'description' => $params['description'] ?? '',
                'image_id' => $params['image_id'],
                'image_list' => $params['image_list'] ?? [], // 多图创意
                'video_id' => $params['video_id'] ?? '', // 视频创意
                'page_type' => $params['page_type'] ?? 'CANVAS',
                'page_url' => $params['page_url'],
                'link_page_type' => $params['link_page_type'] ?? 'LINK_PAGE_TYPE_DEFAULT',
                'link_name_type' => $params['link_name_type'] ?? 'LINK_NAME_TYPE_DEFAULT',
                'preview_url' => $params['preview_url'] ?? '' // 预览链接
            ]);

            $result = [
                'campaign_id' => $campaignId,
                'adgroup_id' => $adgroupId,
                'creative_id' => $creativeId,
                'status' => 'PENDING_REVIEW'
            ];
            return ['code' => 1, 'msg' => '广告创建成功', 'data' => $result];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    
    /**
     * 获取广告统计数据
     * @param string $adId 广告ID
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public function getAdStats($adId, $startDate, $endDate)
    {
        try {
            $fields = [
                'cost', 'impression', 'click', 'ctr',
                'conversion', 'conversion_rate', 'conversion_cost'
            ];
            
            $result = $this->tads->reports()->get([
                'account_id' => $this->accountId,
                'level' => 'REPORT_LEVEL_ADGROUP',
                'date_range' => [
                    'start_date' => $startDate,
                    'end_date' => $endDate
                ],
                'group_by' => ['adgroup_id'],
                'filtering' => [[
                    'field' => 'adgroup_id',
                    'operator' => 'EQUALS',
                    'values' => [$adId]
                ]],
                'fields' => $fields
            ]);

            if (!empty($result->getList())) {
                $data = $result->getList()[0];
                $stats = [
                    'impressions' => $data->getImpression(),
                    'clicks' => $data->getClick(),
                    'spend' => $data->getCost() / 100, // 转换为元
                    'ctr' => $data->getCtr(),
                    'conversions' => $data->getConversion(),
                    'conversion_rate' => $data->getConversionRate(),
                    'conversion_cost' => $data->getConversionCost() / 100 // 转换为元
                ];
            } else {
                $stats = [
                    'impressions' => 0,
                    'clicks' => 0,
                    'spend' => 0,
                    'ctr' => 0,
                    'conversions' => 0,
                    'conversion_rate' => 0,
                    'conversion_cost' => 0
                ];
            }
            return ['code' => 1, 'msg' => '获取成功', 'data' => $stats];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
    
    /**
     * 更新广告状态
     * @param string $adId 广告ID
     * @param string $status 状态
     * @return array
     */
    public function updateAdStatus($adId, $status)
    {
        try {
            $result = $this->tads->adgroups()->update([
                'account_id' => $this->accountId,
                'adgroup_id' => $adId,
                'configured_status' => $status // NORMAL:正常投放, SUSPEND:暂停投放
            ]);
            return ['code' => 1, 'msg' => '状态更新成功', 'data' => $result];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
}